package video

import (
	"github.com/labstack/echo"
	errs "tacitus/library/error"
	"tacitus/library/format"
	resp "tacitus/library/response"
	"tacitus/library/slice/ids"
	"time"
)

func ShowPackageListHandler(c echo.Context) error {
	i := new(resp.PageFields)
	if err := c.Bind(i); err != nil {
		return err
	}
	data := make([]struct{
		Package `xorm:"extends"`
		CreateTimeStr string `json:"create_time_str" xorm:"-"`
	}, 0)
	count, err := rx.OrderBy("create_time DESC").Limit(i.Size(), i.Offset()).FindAndCount(&data)
	if err != nil {
		return err
	}
	for index, item := range data {
		data[index].CreateTimeStr = format.DateTime(item.CreateTime)
	}
	return resp.Page(c, data, *i.SetItemCount(int(count)))
}

func ShowPackageDetailHandler(c echo.Context) error {
	i := new(struct{
		ID int64 `json:"id"`
	})
	if err := c.Bind(i); err != nil {
		return err
	}
	res := new(struct{
		Package `xorm:"extends"`
		VideoList []Video `json:"video_list" xorm:"-"`
		CateList []Category `json:"cate_list" xorm:"-"`
	})
	if ok, err := rx.Where("id = ?", i.ID).Get(res); err != nil {
		return err
	} else if !ok {
		return errs.Called("指定的视频包不存在")
	}
	res.VideoList = make([]Video, 0)
	if err := rx.In("id", ids.FromString(res.VideoIDList)).Find(&res.VideoList); err != nil {
		return err
	}
	ctn := rx.TableName(new(Category))
	atn := rx.TableName(new(Association))
	res.CateList = make([]Category, 0)
	if err := rx.SQL("SELECT c.* FROM `"+ctn+"` AS c JOIN `"+atn+"` AS a ON a.cate_id = c.id AND a.assoc_id = ?", res.ID).Find(&res.CateList); err != nil {
		return err
	}
	return resp.Data(c, res)
}

func CreatePackageHandler(c echo.Context) error {
	i := new(struct{
		Package
		VideoIDList []int64 `json:"video_id_list"`
		CateIDList []int64 `json:"cate_id_list"`
	})
	if err := c.Bind(i); err != nil {
		return err
	}
	now := time.Now().Unix()
	i.ID = 0
	i.Package.VideoIDList = ids.ToString(i.VideoIDList)
	i.CreateTime = now
	if _, err := rx.Insert(&i.Package); err != nil {
		return err
	}
	if len(i.CateIDList) > 0 {
		query := "INSERT INTO t_video_cate_assoc SELECT NULL, id, 'video', ?, ? FROM t_video_cate WHERE id IN ("+ids.ToString(i.CateIDList)+")"
		if _, err := rx.Exec(query, i.ID, now); err != nil {
			return err
		}
	}
	return nil
}

func DeletePackageHandler(c echo.Context) error {
	i := new(struct{
		ID int64 `json:"id"`
	})
	if err := c.Bind(i); err != nil {
		return err
	}
	if _, err := rx.Delete(&Package{ID: i.ID}); err != nil {
		return err
	}
	return nil
}